<template>
  <div class="app-container clipdetail">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.title" clearable class="filter-item" style="width: 200px;" placeholder="请输入名称"/>
      <div class="buttonGroup">
        <el-button class="filter_button" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <el-button class="filter_button" type="primary" @click="allIn">一键入库</el-button>
        <el-button class="filter_button" type="primary" @click.native="handleDownload">全部下载</el-button>
      </div>
    </div>
    <!-- 查询结果 -->
    <MCTable :data-source="dataSource"/>
    <!-- 改标题 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="提示"
      width="30%"
    >
      <el-input v-model="bind_title" placeholder="请输入内容"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureUpdate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 预览 -->
    <el-dialog
      :visible.sync="dialogView"
      :show-close="false"
      title="预览"
      width="25%"
      custom-class="views"
    >
      <div id="mainContainer" class="" style="width:95%;margin:auto;">
        <live-video-area-view
          v-if="video && video.sourceUrl"
          id="mainPlayer"
          ref="mainPlayer"
          :url="video.sourceUrl"
          style="width: 100%; height: 100%;"/>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sureView">确 定</el-button>
      </span>
    </el-dialog>
    <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="sizeChange" />

  </div>
</template>
<script>

import BackToTop from '../../../components/BackToTop'
import Pagination from '../../../components/Pagination'
import ObjectUtil from '../../../utils/object-util'
import { apiVideo as API } from '../../../api/clip/task'
import FileUploader from '../../../components/common/FileUploader'
import RadioMeterialClipResult from './clipResult'
import Fn from '../../../utils/fn'
import { ClipVideoTypeContants, VideoStatusContants } from '../../../mixin/MixinContants'
import { FileUtil } from '../../../utils/file-util'
import LiveVideoAreaView from './views/LiveVideoAreaView'
import tagButton from '../../../components/common/tagButton'
import columns from './clipColumns/detailColumns'

export default {
  name: 'RadioMeterialTaskList',
  components: { RadioMeterialClipResult, FileUploader, BackToTop, Pagination, LiveVideoAreaView, tagButton },
  mixins: [
    ClipVideoTypeContants.mixin,
    VideoStatusContants.mixin
  ],
  data() {
    return {
      // 列表数据源
      dataSource: {
        headerLines: 1,
        list: [],
        columns: columns,
        operates: {
          fixed: 'right',
          list: [
            { label: '修改', type: 'success', show: (row) => (true),
              method: (index, row) => {
                this.handleEdit(row.id, row.inStock)
              }
            },
            { label: '预览', type: 'info', show: (row) => (row.status == 1),
              method: (index, row) => {
                this.views(row)
              }
            },
            { label: '下载', type: 'info', show: (row) => (row.status == 1),
              method: (index, row) => {
                this.oneDownload(row)
              }
            },
            { label: '删除', type: 'info', show: (row) => (true),
              method: (index, row) => {
                this.handleDel(row.id)
              }
            }
          ]
        }
      },
      dialogVisible: false,
      dialogView: false,
      clipId: '',
      bind_title: '',
      page: 1,
      total: 0,
      videotype: '',
      list: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        clipType: 1
        // status:0,
        // sort: 'add_time',
        // order: 'desc'
      },
      dialogStatus: '',

      downloadLoading: false,
      taskId: '',
      taskTitle: '',
      video: { sourceUrl: undefined }
    }
  },
  created() {
    this.taskId = this.$route.query.id
    this.taskTitle = this.$route.query.title
    this.Init()
  },
  methods: {
    sizeChange(val) {
      this.listQuery.limit = val.limit
      this.getList()
    },
    // 预览
    views(row) {
      if (row.meterialMaskUrl) {
        this.video.sourceUrl = row.meterialMaskUrl
      } else if (row.meterialUrl) {
        this.video.sourceUrl = row.meterialUrl
      } else {
        return this.toast.fail('暂时无法预览')
      }
      this.dialogView = true
    },
    sureView() {
      this.dialogView = false
      this.video.sourceUrl = undefined
    },
    // 删除
    handleDel: Fn.Confirm(async function(id) {
      const [err, res] = await this.$await(API.delClip({ id }))
      if (res) {
        this.toast.success('删除成功')
        this.getList()
      }
    }, '确定删除吗？'),

    Init() {
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    async getList() {
      this.$set(this.dataSource, 'options', { loading: true })
      const [err, res] = await this.$await(API.cliplist({ ...this.listQuery, taskId: this.taskId }))
      if (res) {
        this.dataSource.list = res.datas.list || []
        this.total = Number(res.datas.total)
      }
      this.$set(this.dataSource, 'options', { loading: false })
    },
    // 一键入库
    allIn: Fn.Confirm(async function() {
      const [err, res] = await this.$await(API.allIn({ taskId: this.taskId }))
      if (res) {
        this.toast.success('操作成功')
        this.getList()
      }
    }),
    // 全部下载
    handleDownload: Fn.Confirm(function() {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const finalName = (this.taskId || '0') + '_视频下载集合'
      API.cliplist_all({ taskId: this.taskId, clipType: 1 }).then(res => {
        const clipList = res.data.datas.list || []
        const pArr = []
        const fileDataList = []
        clipList.filter(clip => ObjectUtil.notEmpty(clip.meterialUrl)).forEach(clip => {
          fileDataList.push({ filename: clip.title + '.mp4', data: null })
          pArr.push(API.file(clip.meterialUrl)())
        })

        Promise.all(pArr).then(resList => {
          resList.forEach((data, index) => {
            console.log(data, index)
            fileDataList[index].data = data.data
          })
          FileUtil.fileBatchDownload(finalName, fileDataList).then(downRes => {
            this.$notify.success({
              title: '成功',
              message: '下载成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
            })
          }).finally(() => {
            loading.close()
          })
        })
      })
    }),
    // 单独下载
    oneDownload: Fn.Confirm(function(row) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // row.meterialUrl = 'https://seefm-test-1258023332.cos.ap-beijing.myqcloud.com/411f7e1c-ec3f-497d-8960-a75ecb7187cb.mp4'
      const finalName = (row.title || '') + '_视频下载'
      if (ObjectUtil.notEmpty(row.meterialUrl)) {
        const pArr = []
        let fileDataList = []
        fileDataList = [{ filename: row.title + '.mp4', data: null }]
        pArr.push(API.file(row.meterialUrl)())
        Promise.all(pArr).then(resList => {
          console.log(resList, 'reslist')
          resList.forEach((data, index) => {
            console.log(data, index)
            fileDataList[index].data = data.data
          })
          FileUtil.fileBatchDownload(finalName, fileDataList).then(downRes => {
            this.$notify.success({
              title: '成功',
              message: '下载成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
            })
          }).finally(() => {
            loading.close()
          })
        })
      }
    }),

    async sureUpdate() {
      if (this.bind_title == '') return this.toast.fail('请输入标题')
      const [err, res] = await this.$await(API.updateClip({ id: this.clipId, title: this.bind_title }))
      if (res) {
        this.toast.success('更新成功')
        this.getList()
        this.dialogVisible = false
      }
    },
    handleEdit(id, status) {
      // if (status == 1) return this.toast.fail('已入库，请前往素材列表修改')
      // this.clipId = id
      // this.bind_title = ''
      // this.dialogVisible = true
      const { taskId, taskTitle } = this
      this.$router.push({ name: 'RadioMeterialClipEdit', query: { id: taskId, title: taskTitle }})
    }

  }
}
</script>

<style lang='scss' scoped>
  .clipdetail{

  }
</style>
<style>
  .views .el-dialog__body{
      /* padding:0px !important; */
    }
</style>
